<template>
  <div class="name-generator">
    <el-container>
      <el-header>
        <div class="header-content">
          <h1>好名好运AI</h1>
          <el-menu mode="horizontal" router default-active="/name-generator" class="nav-menu">
            <el-menu-item index="/">首页</el-menu-item>
            <el-menu-item index="/name-generator">取名</el-menu-item>
            <el-menu-item index="/history">历史记录</el-menu-item>
            <el-menu-item index="/favorites">收藏</el-menu-item>
          </el-menu>
        </div>
      </el-header>

      <el-main>
        <div class="page-banner">
          <div class="container">
            <h2>智能取名</h2>
            <p>基于传统文化与AI技术，为您的宝宝找到最适合的好名字。</p>
            <p>本网站不保存任何用户信息，请放心使用。</p>
          </div>
        </div>

        <div class="container">
          <el-row :gutter="30">
            <el-col :xs="24" :sm="24" :md="10" :lg="10" :xl="10">
              <el-card class="form-card">
                <template #header>
                  <div class="card-header">
                    <el-icon><EditPen /></el-icon>
                    <span>基本信息</span>
                  </div>
                </template>
                
                <el-form
                  ref="formRef"
                  :model="form"
                  :rules="rules"
                  label-position="top"
                  class="name-form"
                >
                  <el-form-item label="姓氏" prop="surname">
                    <el-input 
                      v-model="form.surname" 
                      placeholder="请输入姓氏"
                      maxlength="1"
                      show-word-limit
                    />
                  </el-form-item>

                  <el-form-item label="名字长度" prop="nameLength">
                    <el-radio-group v-model="form.nameLength" class="name-length-group">
                      <el-radio-button label="2">两字</el-radio-button>
                      <el-radio-button label="3">三字</el-radio-button>
                    </el-radio-group>
                  </el-form-item>

                  <el-form-item label="出生日期" prop="birthDate">
                    <el-date-picker
                      v-model="form.birthDate"
                      type="date"
                      placeholder="选择出生日期"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                      style="width: 100%"
                    />
                  </el-form-item>

                  <el-form-item label="生成模式" prop="modelType">
                    <el-radio-group v-model="form.modelType" class="model-type-group">
                      <el-radio-button label="local">本地生成</el-radio-button>
                      <el-radio-button label="deepseek">DeepSeek</el-radio-button>
                      <el-radio-button label="volcano">火山大模型</el-radio-button>
                    </el-radio-group>
                    <div class="model-description">{{ getModelDescription() }}</div>
                  </el-form-item>

                  <el-form-item label="出生时辰" prop="birthTime">
                    <el-select v-model="form.birthTime" placeholder="请选择出生时辰" style="width: 100%">
                      <el-option label="子时 (23:00-1:00)" value="子时" />
                      <el-option label="丑时 (1:00-3:00)" value="丑时" />
                      <el-option label="寅时 (3:00-5:00)" value="寅时" />
                      <el-option label="卯时 (5:00-7:00)" value="卯时" />
                      <el-option label="辰时 (7:00-9:00)" value="辰时" />
                      <el-option label="巳时 (9:00-11:00)" value="巳时" />
                      <el-option label="午时 (11:00-13:00)" value="午时" />
                      <el-option label="未时 (13:00-15:00)" value="未时" />
                      <el-option label="申时 (15:00-17:00)" value="申时" />
                      <el-option label="酉时 (17:00-19:00)" value="酉时" />
                      <el-option label="戌时 (19:00-21:00)" value="戌时" />
                      <el-option label="亥时 (21:00-23:00)" value="亥时" />
                    </el-select>
                  </el-form-item>

                  <el-form-item label="是否为多胞胎">
                    <el-switch
                      v-model="form.isMultipleBirth"
                      active-text="是"
                      inactive-text="否"
                      @change="handleMultipleBirthChange"
                    />
                  </el-form-item>

                  <el-form-item 
                    v-if="form.isMultipleBirth" 
                    label="多胞胎数量" 
                    prop="multipleCount"
                  >
                    <el-input-number
                      v-model="form.multipleCount"
                      :min="2"
                      :max="5"
                      style="width: 100%"
                      @change="handleMultipleCountChange"
                    />
                  </el-form-item>

                  <div class="gender-section">
                    <div class="section-title">宝宝性别</div>
                    <template v-if="!form.isMultipleBirth">
                      <el-form-item prop="genders.0" class="gender-item">
                        <el-radio-group v-model="form.genders[0]" class="gender-group">
                          <el-radio-button label="男">男孩</el-radio-button>
                          <el-radio-button label="女">女孩</el-radio-button>
                        </el-radio-group>
                      </el-form-item>
                    </template>
                    <template v-else>
                      <el-form-item 
                        v-for="index in form.multipleCount"
                        :key="index"
                        :label="`宝宝${index}`"
                        :prop="`genders.${index - 1}`"
                        class="gender-item"
                      >
                        <el-radio-group 
                          v-model="form.genders[index - 1]" 
                          class="gender-group"
                        >
                          <el-radio-button label="男">男孩</el-radio-button>
                          <el-radio-button label="女">女孩</el-radio-button>
                        </el-radio-group>
                      </el-form-item>
                    </template>
                  </div>

                  <el-form-item label="忌讳的字词" prop="avoidWords">
                    <el-input
                      v-model="form.avoidWords"
                      type="textarea"
                      :rows="3"
                      placeholder="请输入需要避开的字词，多个用逗号分隔"
                    />
                  </el-form-item>

                  <el-form-item class="form-actions">
                    <el-button type="primary" round @click="generateNames" :loading="loading">
                      <el-icon><Magic /></el-icon>
                      开始取名
                    </el-button>
                    <el-button round @click="resetForm">
                      <el-icon><Refresh /></el-icon>
                      重置
                    </el-button>
                  </el-form-item>
                </el-form>
              </el-card>
            </el-col>
            
            <el-col :xs="24" :sm="24" :md="14" :lg="14" :xl="14">
              <el-card class="results-card">
                <template #header>
                  <div class="card-header">
                    <el-icon><List /></el-icon>
                    <span>推荐名字</span>
                    <el-tag 
                      v-if="generatedNames.length" 
                      :type="getModelTypeTagType(generationModelType)" 
                      size="small" 
                      class="generation-tag"
                    >
                      {{ isLocalGeneration ? '本地生成' : getModelTypeDisplay(generationModelType) }}
                    </el-tag>
                  </div>
                </template>
                
                <div v-if="generatedNames.length" class="results-content">
                  <div v-if="form.isMultipleBirth" class="baby-filter">
                    <el-radio-group v-model="currentBabyFilter" size="large">
                      <el-radio-button :label="-1">全部</el-radio-button>
                      <el-radio-button 
                        v-for="index in form.multipleCount" 
                        :key="index" 
                        :label="index-1"
                      >
                        宝宝{{index}}
                      </el-radio-button>
                    </el-radio-group>
                  </div>
                
                  <transition-group name="fade" tag="div" class="name-cards">
                    <el-card 
                      v-for="(nameGroup, index) in filteredNames"
                      :key="index"
                      class="name-card"
                      shadow="hover"
                    >
                      <div v-if="!form.isMultipleBirth">
                        <div class="name-display">
                          <span class="full-name">{{ nameGroup.fullNames[0].fullName }}</span>
                          <div class="card-actions">
                            <el-button type="primary" @click="copyToClipboard(nameGroup)" size="small">
                              复制
                            </el-button>
                            <el-button type="success" @click="saveToFavorites(nameGroup)" size="small">
                              收藏
                            </el-button>
                          </div>
                        </div>
                        
                        <el-divider />
                        
                        <div class="name-details">
                          <div class="detail-row">
                            <div class="detail-item">
                              <div class="detail-label">含义</div>
                              <div class="detail-value">{{ nameGroup.meaning }}</div>
                            </div>
                          </div>
                          
                          <div class="detail-row">
                            <div class="detail-item">
                              <div class="detail-label">五行</div>
                              <div class="detail-value">{{ nameGroup.wuxing }}</div>
                            </div>
                            <div class="detail-item">
                              <div class="detail-label">生肖</div>
                              <div class="detail-value">{{ nameGroup.zodiac }}</div>
                            </div>
                          </div>
                          
                          <div class="detail-row">
                            <div class="detail-item">
                              <div class="detail-label">音韵</div>
                              <div class="detail-value">{{ nameGroup.phonetics }}</div>
                            </div>
                            <div class="detail-item">
                              <div class="detail-label">字形</div>
                              <div class="detail-value">{{ nameGroup.structure }}</div>
                            </div>
                          </div>
                        </div>
                      </div>
                      
                      <div v-else>
                        <div class="name-group-header">
                          <div class="name-group-title">组合{{ index + 1 }}</div>
                          <div class="card-actions">
                            <el-button type="primary" @click="copyToClipboard(nameGroup)" size="small">
                              复制
                            </el-button>
                            <el-button type="success" @click="saveToFavorites(nameGroup)" size="small">
                              收藏
                            </el-button>
                          </div>
                        </div>
                        
                        <div class="related-names">
                          <div 
                            v-for="(name, nIdx) in nameGroup.fullNames" 
                            :key="nIdx"
                            class="related-name-item"
                            :class="{ 'filtered-out': currentBabyFilter !== -1 && currentBabyFilter !== name.babyIndex }"
                          >
                            <div class="related-name-header">
                              <el-tag size="small" class="baby-tag">宝宝{{ name.babyIndex + 1 }}</el-tag>
                              <span class="full-name">{{ name.fullName }}</span>
                            </div>
                          </div>
                        </div>
                        
                        <el-divider />
                        
                        <div class="name-details">
                          <div class="detail-row" v-if="nameGroup.relationMeaning">
                            <div class="detail-item">
                              <div class="detail-label special-label">
                                <el-icon><Link /></el-icon> 关联特点
                              </div>
                              <div class="detail-value highlight">{{ nameGroup.relationMeaning }}</div>
                            </div>
                          </div>
                          
                          <div class="detail-row">
                            <div class="detail-item">
                              <div class="detail-label">含义</div>
                              <div class="detail-value">{{ nameGroup.meaning }}</div>
                            </div>
                          </div>
                          
                          <div class="detail-row">
                            <div class="detail-item">
                              <div class="detail-label">五行</div>
                              <div class="detail-value">{{ nameGroup.wuxing }}</div>
                            </div>
                            <div class="detail-item">
                              <div class="detail-label">生肖</div>
                              <div class="detail-value">{{ nameGroup.zodiac }}</div>
                            </div>
                          </div>
                          
                          <div class="detail-row">
                            <div class="detail-item">
                              <div class="detail-label">音韵</div>
                              <div class="detail-value">{{ nameGroup.phonetics }}</div>
                            </div>
                            <div class="detail-item">
                              <div class="detail-label">字形</div>
                              <div class="detail-value">{{ nameGroup.structure }}</div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </el-card>
                  </transition-group>
                  
                  <div class="more-actions" v-if="generatedNames.length">
                    <el-button type="success" round @click="generateMoreNames" :loading="loading">
                      <el-icon><Plus /></el-icon>
                      再生成一批
                    </el-button>
                  </div>
                </div>
                
                <div v-else class="empty-results">
                  <el-empty 
                    description="填写信息并点击开始取名，AI将为您推荐最合适的名字"
                    :image-size="200"
                  >
                    <template #image>
                      <img src="../assets/baby-name.svg" class="empty-image" alt="准备取名" />
                    </template>
                  </el-empty>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </el-main>
      <Footer />
    </el-container>
  </div>
</template>

<script setup>
import { ref, reactive, watch, nextTick, computed } from 'vue'
import { useNameStore } from '../stores/nameStore'
import { nameService } from '../services/nameService'
import { ElMessage } from 'element-plus'
import { 
  Refresh, 
  Star, 
  List, 
  EditPen, 
  Plus,
  Link,
  MagicStick as Magic 
} from '@element-plus/icons-vue'
import Footer from '../components/Footer.vue'

const store = useNameStore()
const formRef = ref(null)
const loading = ref(false)
const generatedNames = ref([])
const currentBabyFilter = ref(-1) // -1表示显示所有宝宝的名字
const isLocalGeneration = ref(false) // 跟踪是否是本地生成
const generationModelType = ref('local') // 跟踪使用的模型类型

// 根据过滤条件筛选名字
const filteredNames = computed(() => {
  // 非多胞胎情况不需要过滤
  if (!form.isMultipleBirth) {
    return generatedNames.value
  }
  
  if (currentBabyFilter.value === -1) {
    // 显示所有卡片
    return generatedNames.value
  } else {
    // 只过滤卡片而不是完全隐藏卡片
    // 这样用户可以看到所有卡片，但突出显示特定宝宝的名字
    return generatedNames.value
  }
})

const form = reactive({
  surname: '',
  birthDate: '',
  birthTime: '',
  isMultipleBirth: false,
  multipleCount: 2,
  genders: [''],
  avoidWords: '',
  nameLength: '2',
  modelType: 'local'
})

const rules = {
  surname: [
    { required: true, message: '请输入姓氏', trigger: 'blur' },
    { min: 1, max: 1, message: '姓氏只能是一个字', trigger: 'blur' }
  ],
  nameLength: [
    { required: true, message: '请选择名字长度', trigger: 'change' }
  ],
  birthDate: [
    { required: true, message: '请选择出生日期', trigger: 'change' }
  ],
  'genders.0': [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  'genders.1': [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  'genders.2': [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  'genders.3': [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  'genders.4': [
    { required: true, message: '请选择性别', trigger: 'change' }
  ]
}

function handleMultipleBirthChange(value) {
  if (value) {
    form.genders = Array(form.multipleCount).fill('')
  } else {
    form.genders = ['']
  }
  // 清空已生成的名字
  generatedNames.value = []
  // 重置过滤条件
  currentBabyFilter.value = -1
}

function handleMultipleCountChange(value) {
  form.genders = Array(value).fill('')
  // 清空已生成的名字
  generatedNames.value = []
  // 重置过滤条件
  currentBabyFilter.value = -1
}

async function generateNames() {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    store.setUserInput(form)
    
    // 使用本地变量捕获生成方式的信息
    let generationMethod = { isLocal: false, modelType: form.modelType }
    
    const names = await nameService.generateNames(form, generationMethod)
    generatedNames.value = names
    
    // 更新生成方式标志
    isLocalGeneration.value = generationMethod.isLocal
    generationModelType.value = generationMethod.modelType
    
    store.addToHistory(names)
    
    // 重置过滤条件
    currentBabyFilter.value = -1
    
    ElMessage.success('名字生成成功！')
    
    // 移动端视图时滚动到结果区域
    await nextTick()
    if (window.innerWidth <= 992) {
      document.querySelector('.results-card')?.scrollIntoView({ behavior: 'smooth', block: 'start' })
    }
  } catch (error) {
    ElMessage.error('生成名字时出错，请重试')
    console.error(error)
  } finally {
    loading.value = false
  }
}

function generateMoreNames() {
  generateNames()
}

function resetForm() {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  generatedNames.value = []
  currentBabyFilter.value = -1
}

function saveToFavorites(nameGroup) {
  store.saveToFavorites(nameGroup)
  ElMessage.success('名字已收藏')
}

function copyToClipboard(nameGroup) {
  // 构建要复制的文本
  let copyText = '';
  
  // 多胞胎情况下，复制所有名字
  if (nameGroup.fullNames && nameGroup.fullNames.length > 1) {
    copyText = nameGroup.fullNames.map(baby => 
      `${baby.fullName}(${baby.gender})`
    ).join('，');
  } else if (nameGroup.fullNames && nameGroup.fullNames.length === 1) {
    // 单个婴儿的情况
    copyText = nameGroup.fullNames[0].fullName;
  }
  
  // 添加名字含义
  copyText += '\n含义：' + nameGroup.meaning;
  
  // 如果有关联含义，也添加上
  if (nameGroup.relationMeaning) {
    copyText += '\n关联含义：' + nameGroup.relationMeaning;
  }
  
  // 使用Clipboard API复制文本
  navigator.clipboard.writeText(copyText)
    .then(() => {
      ElMessage.success('名字已复制到剪贴板');
    })
    .catch(err => {
      console.error('复制失败：', err);
      ElMessage.error('复制失败，请手动复制');
    });
}

// 获取当前选择模型的描述
function getModelDescription() {
  switch(form.modelType) {
    case 'local':
      return '使用系统内置规则生成名字，无需联网';
    case 'deepseek':
      return '使用DeepSeek AI模型生成更个性化的名字';
    case 'volcano':
      return '使用火山引擎大模型生成更个性化的名字';
    default:
      return '';
  }
}

// 获取模型类型的显示名称
function getModelTypeDisplay(modelType) {
  switch(modelType) {
    case 'local':
      return '本地生成';
    case 'deepseek':
      return 'DeepSeek模型';
    case 'volcano':
      return '火山大模型';
    default:
      return 'AI生成';
  }
}

// 获取当前生成模型的标签类型
function getModelTypeTagType(modelType) {
  switch(modelType) {
    case 'local':
      return 'warning';
    case 'deepseek':
      return 'success';
    case 'volcano':
      return 'primary';
    default:
      return 'info';
  }
}
</script>

<style scoped>
.name-generator {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.el-header {
  background-color: #fff;
  padding: 0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  height: auto;
  min-height: 60px;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 60px;
}

.el-header h1 {
  margin: 0;
  font-size: 24px;
  color: #409EFF;
  white-space: nowrap;
}

.nav-menu {
  border-bottom: none;
  height: 60px;
  background-color: #fff !important;
}

:deep(.el-menu--horizontal) {
  border-bottom: none !important;
}

:deep(.el-menu-item) {
  height: 60px;
  line-height: 60px;
  font-size: 16px;
  color: #2c3e50;
}

:deep(.el-menu-item.is-active) {
  color: #409EFF;
  border-bottom: 2px solid #409EFF;
}

:deep(.el-menu-item:hover) {
  color: #409EFF;
  background-color: transparent;
}

.page-banner {
  padding: 60px 0;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  margin-bottom: 40px;
  text-align: center;
}

.page-banner h2 {
  font-size: 2.5em;
  margin-bottom: 20px;
  color: #2c3e50;
  font-weight: 600;
}

.page-banner p {
  font-size: 1.2em;
  color: #5a6a7f;
  max-width: 600px;
  margin: 0 auto;
}

.container {
  padding: 0 20px;
}

.form-card,
.results-card {
  margin-bottom: 30px;
  transition: all 0.3s;
  height: 100%;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: 500;
}

.generation-tag {
  margin-left: 10px;
  font-size: 12px;
  padding: 2px 6px;
}

.name-form {
  padding: 10px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #2c3e50;
  margin: 10px 0 15px;
}

.gender-section {
  margin: 15px 0;
  border-top: 1px solid #ebeef5;
  padding-top: 15px;
}

.gender-item {
  margin-bottom: 15px;
}

.gender-group {
  width: 100%;
}

.name-length-group {
  width: 100%;
}

.form-actions {
  margin-top: 30px;
  text-align: center;
}

.name-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.name-card {
  transition: all 0.3s ease;
  overflow: hidden;
}

.name-display {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.name-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.baby-tag {
  font-size: 12px;
  padding: 2px 6px;
  margin-right: 5px;
}

.full-name {
  font-size: 28px;
  font-weight: bold;
  color: #409EFF;
}

.save-btn {
  background: #f0f9eb;
  color: #67c23a;
  border: none;
}

.name-details {
  margin-top: 15px;
}

.detail-row {
  display: flex;
  gap: 20px;
  margin-bottom: 15px;
}

.detail-item {
  flex: 1;
}

.detail-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 5px;
}

.detail-value {
  font-size: 15px;
  color: #303133;
  line-height: 1.5;
}

.empty-results {
  min-height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.empty-image {
  width: 200px;
  height: 200px;
  object-fit: contain;
}

.more-actions {
  margin-top: 30px;
  text-align: center;
}

/* 过渡动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 响应式设计 */
@media screen and (max-width: 768px) {
  .header-content {
    flex-direction: column;
    height: auto;
    padding: 10px;
  }

  .el-header h1 {
    margin-bottom: 10px;
  }

  .nav-menu {
    width: 100%;
    justify-content: center;
  }

  .page-banner {
    padding: 40px 15px;
  }

  .page-banner h2 {
    font-size: 1.8em;
  }

  .page-banner p {
    font-size: 1em;
  }

  .name-cards {
    grid-template-columns: 1fr;
  }

  .detail-row {
    flex-direction: column;
    gap: 10px;
  }
}

.baby-filter {
  margin-bottom: 20px;
  display: flex;
  justify-content: center;
}

.name-group-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.name-group-title {
  font-size: 18px;
  font-weight: 600;
  color: #409EFF;
}

.related-names {
  margin: 15px 0;
}

.related-name-item {
  margin-bottom: 10px;
  padding: 8px 12px;
  border-radius: 6px;
  background-color: #f9fafc;
  transition: all 0.3s ease;
  border-left: 3px solid #409EFF;
}

.related-name-item:hover {
  background-color: #ecf5ff;
}

.related-name-item:last-child {
  margin-bottom: 0;
}

.related-name-header {
  display: flex;
  align-items: center;
  gap: 10px;
}

.filtered-out {
  opacity: 0.5;
}

.highlight {
  color: #409EFF;
  font-weight: 500;
}

.special-label {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #409EFF;
  font-weight: 500;
}

.model-type-group {
  width: 100%;
}

.model-description {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
  line-height: 1.4;
}

.card-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}
</style> 